#include<bits/stdc++.h>
using namespace std;
const int N = 1020;
typedef long long LL;
LL mod;
void Mul(LL a[N][N],LL b[],LL c[],int n)
{
	for(int i=1;i<=n;i++)
	c[i]=0;
	for(int i=1;i<=n;i++)
	for(int k=1;k<=n;k++)
	c[i]=(c[i]+1ll*a[i][k]*b[k]%mod)%mod; 
}
int n;
LL a[N][N],b[N][N],c[N][N],A[N],B[N],C[N];
LL e[N][N];
void O()
{
	for(int i=1;i<=n;i++)
	for(int j=1;j<=n;j++)
	for(int k=1;k<=n;k++)
	e[i][j]=(e[i][j]+1ll*a[i][k]*b[k][j]%mod)%mod;
}
template <typename T>inline void read(T &x){
	x=0;char c=getchar();bool f=0;
	for(;c<'0'||c>'9';c=getchar()) f|=(c=='-');
	for(;c>='0'&&c<='9';c=getchar())
	x=(x<<1)+(x<<3)+(c^48);
	x=(f?-x:x);
}
mt19937 rnd(time(0));
LL Make(LL l,LL r)
{
	return rnd()%(r-l+1)+l;
}
void solve()
{
	read(mod);read(n);
	for(int i=1;i<=n;i++)
	for(int j=1;j<=n;j++)
	read(a[i][j]);
	for(int i=1;i<=n;i++)
	for(int j=1;j<=n;j++)
	read(b[i][j]);
	for(int i=1;i<=n;i++)
	for(int j=1;j<=n;j++)
	read(c[i][j]);
	int re=4;
	while(re--)
	{
		for(int i=1;i<=n;i++)
		A[i]=Make(0,mod-1);
		Mul(b,A,B,n);
		Mul(a,B,C,n);
		Mul(c,A,B,n);
		for(int i=1;i<=n;i++)
		if(C[i]!=B[i]) 
		{
			printf("No\n");
			return;
		}		
	}
	printf("Yes\n");
}
int main()
{
	freopen("matrix.in","r",stdin);
	freopen("matrix.out","w",stdout);
	int T;
	cin>>T;
	while(T--)
	{
		solve();
	}
	return 0;
}
